import Common from "../Common/Common";
import EnumData from "../Common/EnumData";
import MyEventListener from "../Common/myEventManger/MyEventListener";
import BaseUI from "../core/BaseUI";
import DataManager from "../core/DataManager";
import DataStorage from "../core/DataStorage";
import ResourcesManager from "../core/ResourcesManager";
import UIManager from "../core/UIManager";
const game = cc.Class({
    extends: BaseUI,

    properties: {
        Mname:{
            default: null,
            type: cc.Label,
            tooltip: '歌曲名称' 
        },
        putBox:{
            default: null,
            type: cc.Node,
            tooltip: '放置盒子' 
        },
        putItem:{
            default: null,
            type: cc.Prefab,
            tooltip: '放置item预制' 
        },
        putItemArr: {
            default: [],
            type: cc.Node,
            tooltip: '放置图标数组'
        },
        targetBox:{
            default: null,
            type: cc.Node,
            tooltip: '目标盒子' 
        },
        targetItem:{
            default: null,
            type: cc.Prefab,
            tooltip: '目标item预制' 
        },
        targetArr:{
            default: [],
            type: cc.Node,
            tooltip: '目标图标数组'
        },

        operation:{
            default: null,
            type: cc.Node,
            tooltip: '操作界面' 
        },
        ending:{
            default: null,
            type: cc.Node,
            tooltip: '结束界面' 
        },
        endIcon:{
            default: null,
            type: cc.Sprite,
            tooltip: '拼接正确节点' 
        },
        xingxing:{
            default: null,
            tooltip: "星星-Node",
            type: cc.Node
        },
        animation:{
            default: null,
            tooltip: "星星-Node",
            type: dragonBones.ArmatureDisplay
        }
    },

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {},

    start() {

    },
    /**初始游戏数据 */
    init(){

        this.xingxing.active = false;
        // if (!this.animation)
        //     this.animation = this.xingxing.getComponent(dragonBones.ArmatureDisplay);

        // console.log(DataManager.GameConfig);
        if (!DataManager.currLevelConfig)
            DataManager.getCurrLevelConfig("DinosaurConfig", DataManager.currLevel);
        // console.log("开始游戏", DataManager.currLevel, DataManager.currLevelConfig);
        this.Mname.string = "LEVEL " + DataManager.currLevel  //DataManager.GameConfig["DinosaurLevel"][DataManager.currLevel].name;
        // httpUtils.httpPost(consts.HTTP_RECORD_SERVER, { title: '达到关卡', content: DataManager.currLevel, desc: null }, function () { });
        this.ending.active = false;
        this.operation.active = true;
        this.putItemArr=[];
        this.targetArr = [];
        this.initPutItems();
        this.initTargets();
        MyEventListener.on(EnumData.EventType.CheckPuzzle, this.onCheckPuzzle, this);
    },
    /**初始防止按钮 */
    initPutItems() {
        // console.log("初始防止按钮111");
        let array = DataManager.currLevelConfig;
        for (let index = 0; index < array.length; index++) {
            const element = array[index];
            let item = ResourcesManager.getObjByPool("putItems", this.putItem);
            item.parent = this.putBox;
            let row = Math.floor(index / 4), col = index % 4;
            item.setPosition(-180 + 125 * col, 161 - row * 84);
            item.getComponent("Puzzle").init(element);
            this.putItemArr.push(item);
        }
        // console.log("初始防止按钮222")
    },
    /**初始目标数组 */
    initTargets() {
        // console.log("初始目标数组111");
        let array = DataManager.currLevelConfig;
        console.log(DataManager.currLevelConfig);
        for (let index = 0; index < array.length; index++) {
            const element = array[index];
            let item = ResourcesManager.getObjByPool("targetItems", this.targetItem);
            item.getComponent("target").init(element);
            item.parent = this.targetBox;
            this.targetArr.push(item);
        }
        // console.log("初始目标数组222");
        this.targetCount = 0;
        this.resultString = []
        this.resultString.length = array.length;
    },

    /**重置结果界面 */
    resetEndings() {
        this.endIcon.spriteFrame = null;
    },
    /**监听拼图放置，判定结果 */
    onCheckPuzzle(param) {
        let minDic, minDicIndex = 0;
        for (let index = 0; index < this.targetArr.length; index++) {
            if (param.puzzleData.id==this.targetArr[index].targetData.id) {
                let worldPos = this.targetArr[index].parent.convertToWorldSpaceAR(this.targetArr[index].getPosition()),
                    dic = Common.distance(worldPos, param.pos);
                (!minDic) ?
                    (minDic = dic, minDicIndex = index) :
                    ((dic < minDic) ? (minDic = dic, minDicIndex = index) : null);
            }
        }
        let maxBorder = Math.min(this.targetArr[minDicIndex].width, this.targetArr[minDicIndex].height);
        maxBorder = Math.pow(maxBorder, 2);
        let result = null;
        if (minDic < maxBorder) {//放置成功
            result = this.targetArr[minDicIndex].getComponent(cc.Sprite).spriteFrame =DataManager.GameConfig[DataManager.currLevel][param.puzzleData.dino]  ;
            // this.targetArr[minDicIndex].putSuccess = true;
            this.targetArr[minDicIndex].data = param.puzzleData;
            this.resultString[minDicIndex]=(param.puzzleData.name);
            this.targetCount++;
            appGame.audioMgr.playSFX("effect");
            this.xingxing.active =true;
            this.animation.playAnimation("xingxing", 1);
        }
        param.cb(result);
        if (this.targetCount >= this.targetArr.length) {
            this.setEnding();
        }
    },


    onClickFinish() {
        DataManager.showRewardedVideo(
            () => {
                for (let index = 0; index < this.targetArr.length; index++) {
                    let data = DataManager.currLevelConfig[index]
                    this.targetArr[index].getComponent(cc.Sprite).spriteFrame = DataManager.GameConfig[DataManager.currLevel][data.dino];
                    this.targetCount++;
                }
                // appGame.audioMgr.playSFX("effect");
                // this.xingxing.active = true;
                // this.animation.playAnimation("xingxing", 1);
                if (this.targetCount >= this.targetArr.length) {
                    this.setEnding();
                }
            },
            () => {

            }
        )

    },

    /**展示结果界面 */
    setEnding() {
        appGame.audioMgr.playSFX("pass");

        this.operation.active = false;
        this.clearGame();

        this.ending.active = true;
        this.endIcon.spriteFrame =DataManager.GameConfig[DataManager.currLevel][ DataManager.GameConfig["DinosaurLevel"][DataManager.currLevel].type]
        this.unlockNextLevel();
        this.timeOutID1212 = setTimeout(() => {
            DataManager.showInterAd();
        }, 2000);
       
    },

    clearGame(){
        for (let index1 = 0; index1 < this.putItemArr.length; index1++) {
            ResourcesManager.putObjToPool("putItems",this.putItemArr[index1]);
        }
        this.putItemArr=[];
        // this.putBox.removeAllChildren();
        for (let index = 0; index < this.targetArr.length; index++) {
            ResourcesManager.putObjToPool("targetItems",this.targetArr[index]);
        }
        this.targetArr = [];
        // this.targetBox.removeAllChildren();
    },


    /**解锁下一关 */
    unlockNextLevel() {
        DataManager.currLevel +=1;
        DataManager.currLevel > DataManager.MaxLevel ?
            (DataStorage.initStorage()) :
            (DataStorage.setLocalData("level", DataManager.currLevel));
        DataManager.currLevel = DataStorage.localData.level;
        DataManager.getCurrLevelConfig("DinosaurConfig", DataManager.currLevel);
        setTimeout(() => {
            this.timeOutID1212&&clearTimeout(this.timeOutID1212)
            this.enterNextLevel();
        }, 4000);
    },

    /**进入下一关 */
    enterNextLevel() {


        UIManager.instance.load.open();

        if (DataManager.GameConfig[DataManager.currLevel]) {
            UIManager.instance.game.close();
            UIManager.instance.load.close();
            UIManager.instance.game.open();
        } else {
            ResourcesManager.loadAtlas("res/"+DataManager.GameConfig["DinosaurLevel"][DataManager.currLevel].type,
            (data, pathName) => {
                UIManager.instance.load.close();
                DataManager.GameConfig[DataManager.currLevel] = Common.arraytoJson(data, "name");
                UIManager.instance.game.close();
                UIManager.instance.game.open();
            });
        }
    },
    /**在玩一遍 */
    playAgain() {
        UIManager.instance.game.close();
        UIManager.instance.game.open();
    },
    open() {
        this._super(arguments);
        DataManager.hideBannerAd();
        this.init();
    },

    close() {
        this._super(arguments);
        this.clearGame();
        MyEventListener.off(EnumData.EventType.CheckPuzzle, this.onCheckPuzzle);
    },
    /**点击返回大厅 */
    onClickBack(event){
        this.close();
        
        UIManager.instance.hall.open()
    },
    // update (dt) {},
});

export default game;
